import { validate as _validate } from 'class-validator';
import { ClassType } from 'class-transformer/ClassTransformer';
import { plainToClass } from 'class-transformer';

export async function validate(instance: Object, skipMissing = false): Promise<string[]> {
    const validationErrors = await _validate(instance, { skipMissingProperties: skipMissing });
    const constraints = validationErrors.map((error) => Object.values(error.constraints!));
    const errors: string[] = [];
    constraints.forEach((constraints) => {
        errors.push(...constraints);
    });
    return errors;
}

export function transform<T>(targetClass: ClassType<T>, plainObject: object): T {
    if (plainObject instanceof targetClass) {
        return plainObject;
    }
    return plainToClass(targetClass, plainObject);
}
